package main

import (
	"fmt"
	"github.com/syndtr/goleveldb/leveldb"
	"os"
	"strconv"
)

func main() {

	if len(os.Args) == 1 {
		fmt.Println("Usage: ./levelshowdata <Database data absolute path> [to show lines num]")
		fmt.Println("if no \\'to show lines num\\', default will show all data!")
		fmt.Println("Example: ./levelshowdata /home/username/dbdata 100")
		return
	}
	if len(os.Args) == 2 {

		db, err2 := leveldb.OpenFile(os.Args[1], nil)
		if err2 != nil {
			fmt.Println(os.Args[1])
			fmt.Println("ERROR: Database can not be opened!")
		}
		iter := db.NewIterator(nil, nil)
		flag := iter.First()
		i := 0
		for flag {
			i++
			flag = iter.Next()
			fmt.Println("index", i, ",key:", string(iter.Key()), ",value:", string(iter.Value()))
		}
	} else {
		nums, err := strconv.Atoi(os.Args[2])
		if err != nil {
			fmt.Println("ERROR: Your input is illegal!")
			return
		}

		db, err2 := leveldb.OpenFile(os.Args[1], nil)
		if err2 != nil {
			fmt.Println(os.Args[1])
			fmt.Println("ERROR: Database can not be opened!")
		}
		iter := db.NewIterator(nil, nil)
		for i := 0; i < nums; i++ {
			iter.Next()
			fmt.Println("index", i, ",key:", string(iter.Key()), ",value:", string(iter.Value()))
		}
	}

}
